package com.tripwego.client.ui.pageVoyage;

import java.util.Date;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.DefaultFormat;
import com.smartgwt.client.util.SC;
import com.tripwego.client.common.TwgConstants;
import com.tripwego.client.event.AddTripEvent;
import com.tripwego.client.event.AddTripEventHandler;
import com.tripwego.client.event.CloseStepEvent;
import com.tripwego.client.event.MajLblInfosEvent;
import com.tripwego.client.model.EtapeModel;
import com.tripwego.client.model.TripModel;
import com.tripwego.client.ui.DialogAttenteWidget;
import com.tripwego.client.ui.widget.IconActiviteWidget;

public class FormCreateEtapeWidget extends FormAbstract implements AddTripEventHandler {

	private String travelMode;

	private String iconUrl;

	private EtapeModel etapePrec;

	private DialogAttenteWidget dialogAttenteWidget = DialogAttenteWidget.getInstance();

	private boolean firstStep = false;

	/*
	 * Elements graphiques
	 */
	private HorizontalPanel viewPanel = new HorizontalPanel();
	protected VerticalPanel panel_aCentrer = new VerticalPanel();
	protected HorizontalPanel panelActions = new HorizontalPanel();
	protected final Button btn_save = new Button("Enregistrer");
	protected final Button btn_cancel = new Button("Fermer");
	protected final FlexTable flexTable = new FlexTable();

	private final HorizontalPanel horizontalPanel_travelType = new HorizontalPanel();
	private final IconActiviteWidget tglbtnUpText_plane = new IconActiviteWidget("airport", TwgConstants.FLIGHT, "En avion");
	private final IconActiviteWidget tglbtnUpText_train = new IconActiviteWidget("train", TwgConstants.RAIL, "En train");
	private final IconActiviteWidget tglbtnUpText_driving = new IconActiviteWidget("car", TwgConstants.DRIVING, "En voiture");
	private final IconActiviteWidget tglbtnUpText_bicycling = new IconActiviteWidget("cycling", TwgConstants.BICYCLING, "A v\u00E9lo");
	private final IconActiviteWidget tglbtnUpText_walking = new IconActiviteWidget("hiking", TwgConstants.WALKING, "A pied");
	private final IconActiviteWidget tglbtnUpText_boat = new IconActiviteWidget("boat", TwgConstants.BOAT, "En bateau");
	private final IconActiviteWidget tglbtnUpText_nothing = new IconActiviteWidget("stargate", TwgConstants.NOTHING, "Pas de trajet");
	private final Label lblArrive = new Label("Nouvelle \u00E9tape");
	private final TextBox textBox_end = new TextBox();
	private final Label lblDateDeDpart = new Label("Arriv\u00E9e");
	private final DateBox dateBox_start = new DateBox();
	private final Label lblDateDarrive = new Label("D\u00E9part");
	private final DateBox dateBox_end = new DateBox();
	private final Label lbl_travelType = new Label("Comment ?");

	/**
	 * 
	 */
	public FormCreateEtapeWidget() {
		super();

		viewPanel.setStyleName("divCenter_FormulaireWidget");

		viewPanel.add(panel_aCentrer);
		viewPanel.setCellHorizontalAlignment(panel_aCentrer, HasHorizontalAlignment.ALIGN_CENTER);

		panel_aCentrer.setStyleName("FormulaireWidget");

		panel_aCentrer.add(flexTable);
		// flexTable.setWidth("100%");
		panel_aCentrer.setCellWidth(flexTable, "1%");

		lblArrive.setWordWrap(false);

		flexTable.setWidget(0, 0, lblArrive);
		textBox_end.setVisibleLength(40);

		flexTable.setWidget(0, 1, textBox_end);

		// definition de l'id pour js
		textBox_end.getElement().setId(TwgConstants.AUTOCOMPLETE_NEXT_ETAPE);

		textBox_end.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				presenter.majValidationAutocomplete(TwgConstants.AUTOCOMPLETE_NEXT_ETAPE, false);
			}
		});
		flexTable.getCellFormatter().setHorizontalAlignment(2, 1, HasHorizontalAlignment.ALIGN_CENTER);
		lblDateDeDpart.setWordWrap(false);

		flexTable.setWidget(1, 0, lblDateDeDpart);
		dateBox_start.setFormat(new DefaultFormat(DateTimeFormat.getShortDateFormat()));

		flexTable.setWidget(1, 1, dateBox_start);
		dateBox_start.setWidth("80px");
		lblDateDarrive.setWordWrap(false);

		flexTable.setWidget(1, 2, lblDateDarrive);
		dateBox_end.setFormat(new DefaultFormat(DateTimeFormat.getShortDateFormat()));

		flexTable.setWidget(1, 3, dateBox_end);
		dateBox_end.setWidth("80px");

		flexTable.setWidget(2, 0, lbl_travelType);
		horizontalPanel_travelType.setStyleName("travelType");

		flexTable.setWidget(2, 1, horizontalPanel_travelType);
		horizontalPanel_travelType.setWidth("");

		horizontalPanel_travelType.add(tglbtnUpText_plane);

		horizontalPanel_travelType.add(tglbtnUpText_train);

		horizontalPanel_travelType.add(tglbtnUpText_boat);

		horizontalPanel_travelType.add(tglbtnUpText_driving);

		horizontalPanel_travelType.add(tglbtnUpText_bicycling);

		horizontalPanel_travelType.add(tglbtnUpText_walking);

		horizontalPanel_travelType.add(tglbtnUpText_nothing);
		flexTable.getFlexCellFormatter().setColSpan(0, 1, 3);
		flexTable.getFlexCellFormatter().setColSpan(2, 1, 3);

		tglbtnUpText_bicycling.addClickHandler(this);
		tglbtnUpText_boat.addClickHandler(this);
		tglbtnUpText_driving.addClickHandler(this);
		tglbtnUpText_plane.addClickHandler(this);
		tglbtnUpText_train.addClickHandler(this);
		tglbtnUpText_walking.addClickHandler(this);
		tglbtnUpText_nothing.addClickHandler(this);

		panelActions.setSpacing(10);
		panelActions.add(btn_save);
		panelActions.setCellWidth(btn_save, "1%");
		panelActions.add(btn_cancel);

		panel_aCentrer.add(panelActions);

		btn_save.addClickHandler(this);
		btn_cancel.addClickHandler(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.google.gwt.user.client.ui.Widget#asWidget()
	 */
	@Override
	public Widget asWidget() {
		return viewPanel;
	}

	public void initToggleBtn() {
		tglbtnUpText_bicycling.setValue(TwgConstants.BICYCLING.equals(travelMode));
		tglbtnUpText_boat.setValue(TwgConstants.BOAT.equals(travelMode));
		tglbtnUpText_driving.setValue(TwgConstants.DRIVING.equals(travelMode));
		tglbtnUpText_plane.setValue(TwgConstants.FLIGHT.equals(travelMode));
		tglbtnUpText_train.setValue(TwgConstants.RAIL.equals(travelMode));
		tglbtnUpText_walking.setValue(TwgConstants.WALKING.equals(travelMode));
		tglbtnUpText_nothing.setValue(TwgConstants.NOTHING.equals(travelMode));
	}

	@Override
	public void onClick(ClickEvent event) {
		Object sender = event.getSource();

		if (sender instanceof IconActiviteWidget) {
			IconActiviteWidget iconActiviteWidget = (IconActiviteWidget) sender;
			travelMode = iconActiviteWidget.getType();
			iconUrl = iconActiviteWidget.getIconUrldown();
			initToggleBtn();
		}
		if (sender == btn_save) {

			boolean erreur = false;
			removeAllError();

			if (!firstStep && travelMode == null) {
				horizontalPanel_travelType.setStyleDependentName("error", true);
				horizontalPanel_travelType.setTitle("Selectionnez un mode de transport");
				erreur = true;
			}

			if (dateBox_start.getValue() == null || dateBox_start.getValue().toString().isEmpty()) {
				dateBox_start.setStyleDependentName("error", true);
				erreur = true;

			}
			if (dateBox_end.getValue() == null || dateBox_end.getValue().toString().isEmpty()) {
				dateBox_end.setStyleDependentName("error", true);
				erreur = true;

			}

			if (textBox_end.getValue() == null || textBox_end.getValue().toString().isEmpty()
					|| !presenter.isAutocompleteValide(TwgConstants.AUTOCOMPLETE_NEXT_ETAPE)) {
				textBox_end.setStyleDependentName("error", true);
				textBox_end.setTitle("Selectionnez un lieu dans la liste");
				textBox_end.setFocus(true);
				erreur = true;
			}

			if (!erreur) {
				Date dateStart = dateBox_start.getValue();
				Date dateEnd = dateBox_end.getValue();

				if (dateStart.compareTo(dateEnd) >= 0) {
					dateBox_end.setStyleDependentName("error", true);
					SC.warn("La date de depart doit etre superieure a la date d'arrivee");
					erreur = true;
				}
			}

			if (!erreur) {
				dialogAttenteWidget.initMessage(DialogAttenteWidget.MESSAGE_ENREGISTREMENT);
				dialogAttenteWidget.show();

				if (firstStep) {
					TripModel tripModel = new TripModel();

					tripModel.setDateDebTrip(dateBox_start.getValue());
					tripModel.setDateFinEtape1(dateBox_end.getValue());
					tripModel.setAddressStart(textBox_end.getValue());

					presenter.onCreateTrip(tripModel);
				} else {
					EtapeModel etapeModel = new EtapeModel();
					etapeModel.setFirstStep(firstStep);
					etapeModel.setTravelMode(travelMode);
					etapeModel.setAddress(textBox_end.getValue());
					etapeModel.setIconUrl(iconUrl);
					etapeModel.setDateDeb(dateBox_start.getValue());
					etapeModel.setDateFin(dateBox_end.getValue());

					etapePrec = etapeModel;

					presenter.onCreateEtape(etapeModel);

					init();
				}
			}
		}
		if (sender == btn_cancel) {
			eventBus.fireEvent(new CloseStepEvent());
			eventBus.fireEvent(new MajLblInfosEvent(""));

			hide();
		}
	}

	@Override
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;

		// ecouteurs d'evenements
		eventBus.addHandler(AddTripEvent.TYPE, this);
	}

	@Override
	public void init() {

		firstStep = (etapePrec == null);

		// presenter.initAutocomplete(TwgConstants.AUTOCOMPLETE_ID_STEP_END,
		// "geocode");
		presenter.majValidationAutocomplete(TwgConstants.AUTOCOMPLETE_NEXT_ETAPE, false);

		travelMode = null;
		initToggleBtn();
		textBox_end.setValue("");

		removeAllError();

		Date dateStart = null;

		if (firstStep) {
			dateStart = new Date();
			dateBox_start.setEnabled(true);
			lbl_travelType.setVisible(false);
			horizontalPanel_travelType.setVisible(false);
			btn_cancel.setVisible(false);
		} else {
			dateStart = etapePrec.getDateFin();
			dateBox_start.setEnabled(false);
			lbl_travelType.setVisible(true);
			horizontalPanel_travelType.setVisible(true);
			btn_cancel.setVisible(true);
		}

		Date dateEnd = CalendarUtil.copyDate(dateStart);
		CalendarUtil.addDaysToDate(dateEnd, 1);

		dateBox_start.setValue(dateStart);
		dateBox_end.setValue(dateEnd);
	}

	/**
	 * suppression des erreurs
	 */
	public void removeAllError() {
		textBox_end.setStyleDependentName("error", false);
		dateBox_start.setStyleDependentName("error", false);
		dateBox_end.setStyleDependentName("error", false);
		textBox_end.setTitle(null);
		horizontalPanel_travelType.setStyleDependentName("error", false);
		horizontalPanel_travelType.setTitle(null);
	}

	/**
	 * @return the etapePrec
	 */
	public EtapeModel getEtapePrec() {
		return etapePrec;
	}

	/**
	 * @param etapePrec
	 *            the etapePrec to set
	 */
	public void setEtapePrec(EtapeModel etapePrec) {
		this.etapePrec = etapePrec;
	}

	@Override
	public void handleAddTripEvent(AddTripEvent event) {
		TripModel tripModel = event.getTripModel();

		etapePrec = new EtapeModel();
		etapePrec.setFirstStep(true);
		etapePrec.setAddress(tripModel.getAddressStart());
		etapePrec.setDateDeb(tripModel.getDateDebTrip());
		etapePrec.setDateFin(tripModel.getDateFinEtape1());
		etapePrec.setName(tripModel.getAddressStart());

		init();
	}
}
